package cn.zhagzheguo.xk.core;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 封装好的mybatis单例，由于更改为spring管理sessionfactory，该类未使用
 * 
 * @author zhagz
 * 
 */
public class SessionFactory {

	private static SqlSessionFactory sqlSessionFactory = null;

	private static void init() throws IOException {
		String resource = SessionFactory.class.getResource("/").getPath().substring(1).split("/target/test-classes/")[0]
				+ "/MybatisConfig.xml";
		resource = "MybatisConfig.xml";

		System.out.println(resource);
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}

	/**
	 * 得到一个新的session
	 * 
	 * @return
	 */
	public static SqlSession getSession() {
		try {
			if (sqlSessionFactory == null) {
				init();
			}
			return sqlSessionFactory.openSession();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

}
